package com.whz.parameterized;

import java.util.EmptyStackException;

/**
 * @Author: sinosoft
 * @Description:
 * @Date: Create in 17:06 2021/5/11
 * @Modified By:
 */
public class Stack<E> {
    private E[] elements;
    private int size = 0;
    private static final int DEFAULT_INITIAL_CAPACITY = 16;

    /*消除编译时期未受检查警告*/
    @SuppressWarnings("unchecked")
    public Stack() {
        /*
        * 无法创建泛型数组 需要创建一个Object数组 并将它转换成泛型数组类型
        * */
        elements = (E[]) new Object[DEFAULT_INITIAL_CAPACITY];
    }

    public void push(E e) {
        elements[size++] = e;
    }
    public E pop() {
        if(size == 0) {
            throw new EmptyStackException();
        }
        E result = elements[--size];
        elements[size] = null;
        return result;
    }
}
